package com.winshare.saleAssistant.util;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

public class CaptchaUtils {

    private static final int CAPTCHA_WIDTH = 450;
    private static final int CAPTCHA_HEIGHT = 100;
    private static final int CAPTCHA_CODE_COUNT = 4;
    private static final String FONT_NAME = "Fixedsys";
    private static final int CAPTCHA_FONT_HEIGHT = 80;
    private static final int OFFSET_X = 75;
    private static final int CAPTCHA_CODE_Y = 80;
    private static final char[] CODE_SEQUENCE = new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};

    private CaptchaUtils() {
        throw new UnsupportedOperationException("u can't instantiate me...");
    }

    public static Tuple2<String, BufferedImage> getCaptchaImage() {
        return getCaptchaImage(450, 100);
    }

    public static Tuple2<String, BufferedImage> getCaptchaImage(int width, int height) {
        BufferedImage bufferedImage = new BufferedImage(width, height, 1);
        Graphics2D graphics2D = bufferedImage.createGraphics();
        Random random = new Random();
        graphics2D.setColor(new Color(247, 247, 247));
        graphics2D.fillRect(0, 0, width, height);
        graphics2D.setFont(new Font("Fixedsys", 1, 80));
        graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        StringBuilder randomCode = new StringBuilder();

        for(int i = 0; i < 4; ++i) {
            String code = String.valueOf(CODE_SEQUENCE[random.nextInt(36)]);
            graphics2D.setColor(new Color(21, 96, 152));
            graphics2D.drawString(code, (i + 1) * 75, 80);
            randomCode.append(code);
        }

        return Tuple2.of(randomCode.toString(), bufferedImage);
    }

    public static String getCaptchaCode() {
        return getCaptchaCode(4);
    }

    public static String getCaptchaCode(int length) {
        StringBuilder randomCode = new StringBuilder();
        Random random = new Random();

        for(int i = 0; i < length; ++i) {
            String code = String.valueOf(CODE_SEQUENCE[random.nextInt(10) + 26]);
            randomCode.append(code);
        }

        return randomCode.toString();
    }
}
